package com.meisen.springboot.service.impl;

import com.meisen.springboot.entity.IpBlackList;
import com.meisen.springboot.repo.IpBlackListRepository;
import com.meisen.springboot.service.IpBlackListService;
import com.meisen.springboot.service.redis.IpBlackListRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * ip黑名单
 * @author meisen
 * 2018-05-08
 */
@Service
public class IpBlackListServiceImpl implements IpBlackListService {

    private final IpBlackListRepository ipBlackListRepository;
    private final IpBlackListRedisService ipBlackListRedisService;

    @Autowired
    public IpBlackListServiceImpl(IpBlackListRepository ipBlackListRepository, IpBlackListRedisService ipBlackListRedisService) {
        this.ipBlackListRepository = ipBlackListRepository;
        this.ipBlackListRedisService = ipBlackListRedisService;
    }

    @Override
    public List<IpBlackList> findAll() {
        List<IpBlackList> ipBlackLists = ipBlackListRedisService.getAll();
        if (isNullOrEmpty(ipBlackLists)) {
            ipBlackLists = ipBlackListRepository.findAll();
            ipBlackLists.forEach(ipBlackList -> ipBlackListRedisService.put(ipBlackList.getIp(), ipBlackList, -1));
        }
        return ipBlackLists;
    }

    @Override
    public IpBlackList findByIp(String ip) {
        IpBlackList ipBlackList = ipBlackListRedisService.get(ip);
        ipBlackList = null == ipBlackList ? ipBlackListRepository.findByIp(ip) : ipBlackList;
        if (ipBlackList != null) {
            ipBlackListRedisService.put(ip, ipBlackList, -1);
        }
        return ipBlackList;
    }

    @Override
    public void addIpBlackList(IpBlackList ipBlackList) {
        ipBlackListRepository.save(ipBlackList);
        ipBlackListRedisService.put(ipBlackList.getIp(), ipBlackList, -1);
    }

    @Override
    public void deleteByIp(String ip) {
        ipBlackListRepository.deleteIpBlackListByIp(ip);
        ipBlackListRedisService.remove(ip);
    }

    @Override
    public void clearCache() {
        ipBlackListRedisService.emptyHash();
    }

    private boolean isNullOrEmpty(Collection<?> collection) {
        return null == collection || collection.isEmpty();
    }
}
